package cn.phecda.boot.data.mybatis.support;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.List;

/**
 * <p> 分页适配器 </p>
 *
 * @author : wanpinwei
 */
public class PageAdapter<T> extends com.baomidou.mybatisplus.extension.plugins.pagination.Page<T> {
    public static <T> IPage<T> of(Pageable pageable) {
        // spring data 分页从0开始：https://github.com/spring-projects/spring-boot/issues/14413
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<T> page =
                com.baomidou.mybatisplus.extension.plugins.pagination.Page.of(pageable.getPageNumber() + 1, pageable.getPageSize());

        // 排序条件
        List<OrderItem> orderItems = pageable.getSort()
                .get()
                .map(order -> {
                    if (Sort.Direction.DESC.equals(order.getDirection())) {
                        return OrderItem.desc(order.getProperty());
                    } else {
                        return OrderItem.asc(order.getProperty());
                    }
                })
                .toList();
        page.addOrder(orderItems);
        return page;
    }

    public static <T> org.springframework.data.domain.Page<T> of(IPage<T> ipage) {
        List<Sort.Order> orders = ipage.orders().stream()
                .map(orderItem -> {
                    if (orderItem.isAsc()) {
                        return Sort.Order.asc(orderItem.getColumn());
                    } else {
                        return Sort.Order.desc(orderItem.getColumn());
                    }
                })
                .toList();

        Pageable pageable = PageRequest.of((int) ipage.getCurrent() - 1, (int) ipage.getSize(), Sort.by(orders));
        return new PageImpl<>(ipage.getRecords(), pageable, ipage.getTotal());
    }
}
